package com.laamella.syntherface.midi;

import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;

public class MidiHandler {

	public static final MidiHandler midiHandler = new MidiHandler();
	public final List<MidiDevice.Info> receivers = new ArrayList<MidiDevice.Info>();
	public final List<MidiDevice.Info> transmitters = new ArrayList<MidiDevice.Info>();

	private MidiHandler() {
		refresh();
	}

	public void refresh() {
		receivers.clear();
		transmitters.clear();
		for (MidiDevice.Info info : MidiSystem.getMidiDeviceInfo()) {
			System.out.println(info.getName() + ": " + info.getDescription());
			try {
				MidiDevice midiDevice = MidiSystem.getMidiDevice(info);


				boolean wasOpen = midiDevice.isOpen();
				if (!wasOpen) {
					midiDevice.open();
				}
				try {
					if (midiDevice.getMaxReceivers() != 0) {
						receivers.add(info);
					}
					if (midiDevice.getMaxTransmitters() != 0) {
						transmitters.add(info);
					}
				} finally {
					if (!wasOpen) {
						midiDevice.close();
					}
				}
			} catch (MidiUnavailableException ex) {
				System.out.println("Can't query device " + info.getName());
				ex.printStackTrace();
			}
		}

	}

	public void close() {
	}
}
